#include "SvrList.h"

#ifdef __linux__
#include <netdb.h>
#include <unistd.h>
#endif


#include "SocketUtils.h"

CSvrList * g_svrList;

CSvrList * CSvrList::m_pSvrList;
OSMutex	   CSvrList::m_svrListMutex;
vector<svrListElem> CSvrList::m_svrList;;

CSvrList::CSvrList()
{
	m_svrList.clear();
}

CSvrList::~CSvrList()
{

}

CSvrList* CSvrList::GetInstance()
{
	if (m_pSvrList == NULL) {
		m_pSvrList = new CSvrList();
	}
	return m_pSvrList;
}

void CSvrList::DelInstance()
{
	if(m_pSvrList)
	{
		delete m_pSvrList;
		m_pSvrList = NULL;
	}
}

UInt16 CSvrList::SetSvrList(char** sIPAddr, UInt16 listLen)
{
	svrListElem oneSvr;
	int i;

	hostent* myhost;
	char	hostname[40];
	
	gethostname(hostname, 128);
	myhost = gethostbyname( hostname );
	
	char	buf[20] = {0};
	
	sprintf(buf, "%d.%d.%d.%d", 
		(myhost->h_addr_list[0][0]) & 0x00ff,
		(myhost->h_addr_list[0][1]) & 0x00ff,
		(myhost->h_addr_list[0][2]) & 0x00ff,
		(myhost->h_addr_list[0][3]) & 0x00ff);
	
	for( i= 0; i < listLen; i++)
	{
/*
					if ( !strcmp( sIPAddr[i], buf ) )
						continue;*/
			
		strcpy(	oneSvr.strIP, sIPAddr[i]);
//		oneSvr.iIP = SocketUtils::ConvertStringToAddr(sIPAddr[i]);
		m_svrListMutex.Lock();
		m_svrList.push_back(oneSvr);
		m_svrListMutex.Unlock();
	}	
	return (UInt16)m_svrList.size();
}

Bool CSvrList::AddSvr( char* sIPAddr, UInt16 port)
{
	svrListElem oneSvr={0} ;
	
	/*
	hostent* myhost;
		char	hostname[40];	
		gethostname(hostname, 128);
		myhost = gethostbyname( hostname );
		
		char	buf[20] = {0};	
		sprintf(buf, "%d.%d.%d.%d", 
			(myhost->h_addr_list[0][0]) & 0x00ff,
			(myhost->h_addr_list[0][1]) & 0x00ff,
			(myhost->h_addr_list[0][2]) & 0x00ff,
			(myhost->h_addr_list[0][3]) & 0x00ff);
	/ *
				if ( !strcmp( sIPAddr, buf ) )
					return FALSE;* /*/
		
	strcpy(	oneSvr.strIP, sIPAddr);
	
//	oneSvr.iIP = SocketUtils::ConvertStringToAddr(sIPAddr);
	oneSvr.port = port;
	m_svrListMutex.Lock();
	m_svrList.push_back( oneSvr );
	m_svrListMutex.Unlock();
	
	return TRUE;
}

/*
UInt32	CSvrList::GetOneSvrAddrI(int readListAt)
{
	if ( readListAt >= m_svrList.size()) 
		return(0) ;		
	
	svrListElem&	oneSvr = m_svrList.at( readListAt );
	
	
	return(oneSvr.iIP) ;
}*/


char*	CSvrList::GetOneSvrAddrS(int readListAt)
{
	if ( readListAt >= m_svrList.size()) 
		return(0) ;		
	
	svrListElem&	oneSvr = m_svrList.at( readListAt );		
	
	return(oneSvr.strIP) ;
}

UInt16	CSvrList::GetPort(int readListAt)
{
	if ( readListAt >= m_svrList.size()) 
		return(0) ;		
	
	svrListElem&	oneSvr = m_svrList.at( readListAt );		
	
	return(oneSvr.port) ;
}
